package cn.chenyumeng.blog.service.blog.impl;

import cn.chenyumeng.blog.dto.BlogDTO;
import cn.chenyumeng.blog.entity.Blog;
import cn.chenyumeng.blog.entity.BlogTag;
import cn.chenyumeng.blog.mapper.BlogMapper;
import cn.chenyumeng.blog.mapper.BlogTagMapper;
import cn.chenyumeng.blog.mapper.CommentMapper;
import cn.chenyumeng.blog.service.blog.TypePageServer;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: blog->TypePageServerImpl
 * @description:
 * @author: cg
 * @create: 2020-08-23 18:50
 **/
@Service
public class TypePageServerImpl implements TypePageServer {

    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private BlogTagMapper blogTagMapper;

    @Autowired
    private CommentMapper commentMapper;

    @Override
    public PageInfo<BlogDTO> getBlogListLimitByTypeId(Integer page, Integer size, Integer id) {
        PageHelper.startPage(page, size);
        List<Blog> blogs = blogMapper.queryBlogListByLatestPublishedAndTypeId(id);
        if (blogs.isEmpty()) {
            return null;
        }
        PageInfo blogPageInfo = new PageInfo(blogs);
        List<BlogDTO> dtoList = new ArrayList<>();
        blogPageInfo.getList().forEach(blog -> {
            BlogDTO blogDTO = new BlogDTO();
            BeanUtils.copyProperties(blog, blogDTO);
            blogDTO.setTagIds(getTagIds(blogDTO.getId()));
            blogDTO.setCommentCount(commentMapper.queryBlogCommentCountByBlogId(blogDTO.getId()));
            dtoList.add(blogDTO);
        });
        blogPageInfo.setList(dtoList);
        return blogPageInfo;
    }

    /**
     * 通过blogId查询所对应的tagIds
     * @param blogId
     * @return
     */
    private List<Long> getTagIds(Long blogId) {
        List<BlogTag> blogTags = blogTagMapper.selectBlogTagsByBlogId(blogId);
        List<Long> tags = new ArrayList<>();
        blogTags.forEach(blogTag -> tags.add(blogTag.getTagId()));
        return tags;
    }
}
